<?php

namespace app\api\controller;

use app\api\model\Config as ConfigModel;
use app\api\model\GoodsComment as GoodsCommentModel;
use app\api\model\UserShop;
use app\common\controller\Api;
use app\api\model\User as UserModel;
use app\api\model\Goods as GoodsModel;
use app\api\model\UserShop as UserShopModel;
use app\api\model\Vehicle as VehicleModel;
use app\api\model\Brand as BrandModel;
use EasyWeChat\Kernel\Messages\News;
use think\Model;
use think\Validate;
use think\Db;

/**
 * 商品接口
 */
class Goods extends Api
{
    protected $noNeedLogin = [
        'getGoods',
        'Goodsshop',
        'Goodslist',
        'goodsitem'
    ];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }
    /**
     *商品详情
     *
     */
    public function getGoods()
    {
        $uid = $this->auth->id;
        $id = $this->request->param('id');
        $lat = $this->request->param('lat', ''); // 纬度
        $lng = $this->request->param('lng',''); //经度
        $UserModel = new UserModel();
        // 获取用户信息
        $userInfo = $UserModel->getUserInfo($uid);

        $GoodsModel = new GoodsModel();
        // 获取商品规格
        $goodsList  = $GoodsModel->getGoodsDetail($userInfo,$id);

        if (empty($goodsList['status'])) $this->success($goodsList['msg'],'',200);

        $goodshot = $GoodsModel->Getgoodshot($userInfo);  //热门推荐

        //商品参数
        $parameter = json_decode($goodsList['data']['parameter'],true);

        //获取品牌
        $BrandModel = new BrandModel();

        $banner_name = $BrandModel->getBrand($goodsList['data']['brand_id']);

        $goodsList['data']['brand_id'] = empty($banner_name) ? '' : $banner_name;

        //获取车型
        $VehicleModel = new VehicleModel();
        $models = $VehicleModel->getVehicle($goodsList['data']['models_id']);
        $models = empty($models['status']) ? [] : $models['data'];

        //商品轮播图
        $banner = $goodsList['data']['shuff_image'] ? explode(',',$goodsList['data']['shuff_image']) : [];
        unset($goodsList['data']['shuff_image']);
        $UserShopModel = new UserShopModel();

        //评论
        $goods_comment  = Db::name('goods_comment')
            ->where('gid',$id)
            ->where('status',0)
            ->where('goods_type','goods')
            ->order('score desc')
            ->find();
        if (!empty($goods_comment['image']))
        {
            $goods_comment['image'] = explode(',', $goods_comment['image']);
        }

        // 商品组合
        $collocation = $GoodsModel->Getcombination($id,$userInfo);

        if ($collocation)
        {
            foreach($collocation as $key => $value){
                $collocation[$key]['name']       = \app\api\model\Goods::where('id',$value['child_goods_id'])->value('name');
                $collocation[$key]['main_image'] = \app\api\model\Goods::where('id',$value['child_goods_id'])->value('main_image');
            }
        }
        $goodsList['data']['category_id'] = Db::name('goods_addcategory')
            ->where('gid',$goodsList['data']['id'])
            ->column('category_id');
        $shoptype = $UserShopModel->getShop($goodsList['data']['category_id'], $name = '', $lat, $lng);

        $this->success('获取成功',[
            'hot'     => $goodshot,
            'comment' => empty($goods_comment) ? '' : $goods_comment,
            'list'    => $goodsList['data'],
            'models'  => $models,
            'parameter' => $parameter,
            'banner'    => $banner,
            'collocation' => $collocation,
            'shoptype'    => $shoptype], 200);
    }
    /**
     * 商品规格
     */
    public function goodsitem()
    {
        $uid = $this->auth->id;
        $params = $this->request->param();
        if (!$params['id'] || !$params['name'])
        {
            $this->success('参数错误', '', 400);
        }
        $where = [];
        $where['goods_id']   = ['eq', $params['id']];
        $where['spec_value_str'] = ['eq', $params['name']];
        $item = Db::name('goods_item')->field('weight,spec',true)->where($where)->find();

        if (!$item)
        {
            $this->success('商品不存在或已下架', '', 400);
        }

        $UserModel = new UserModel();
        $user = $UserModel->getUserInfo($uid);
        $ConfigModel = new ConfigModel();
        if ($user['is_vip'] == 0)
        {
            $item['price'] = $item['ordinaryprice'];
        }elseif($user['is_vip'] == 1){

            $item['price'] = $item['haveprice'];
        }elseif($user['is_vip'] == 2){


            if ($item['agentprice'] != 0)
            {
                $item['price'] = $item['agentprice'];
            }else{
                $agent_price = $ConfigModel->getAgent();
                $item['price'] = $agent_price == 0 ? $item['ordinaryprice'] : $item['haveprice'] * $agent_price;
            }
        }elseif ($user['is_vip'] == 3){
            if ($item['agentprice'] != 0)
            {
                $item['price'] = $item['agentprice'];
            }else{
                $agent_price = $ConfigModel->getOneAgent();
                $item['price'] = $agent_price == 0 ? $item['ordinaryprice'] : $item['haveprice'] * $agent_price;
            }

        }

        $this->success('获取成功',$item,200);
    }
    /**
     * 商品列表
     */
    public function Goodslist()
    {
        $name        = $this->request->param('name','');
        $page        = $this->request->param('page',1);
        $limit       = $this->request->param('limit',20);
        $sales_sum   = $this->request->param('sales_sum',0);
        $order_price = $this->request->param('order_price',0);
        $high_price  = $this->request->param('high_price',''); //最高价格
        $low_price   = $this->request->param('low_price',''); //最低价格
        $cartgory    = $this->request->param('cartgory',''); //最低价格
        $uid = $this->auth->id;
        $UserShopModel = new GoodsModel();
        $Goodsdata = $UserShopModel->Getgoodslist($name, $uid, $limit, $page, $sales_sum, $order_price,$high_price,$low_price,$cartgory);
        $list = $Goodsdata->items();
        if ($name != ""){
            shuffle($list);
        }
        $this->success('查询成功',['list' => $list, 'count' => $Goodsdata->total()],200);
    }
    /**
     * 安装店详情
     */
    public function Goodsshop()
    {
        $uid = $this->auth->id;
        $id = $this->request->param('id');
        $userlng = $this->request->param('lng');
        $userlat = $this->request->param('lat');

        if (!$id) $this->success('缺失参数', '', 400);
        $UserShopModel = new UserShopModel();
        // 安装店信息
        $Goodsshopdata = $UserShopModel->Getshopinfo($id, $userlng, $userlat,$uid);

        //评论信息
        $count = GoodsCommentModel::where('gid',$id)->where('goods_type','shop')->where('score', '>', 3)->count();
        $Goodsshopdata['data']['count'] = $count;


        if ($Goodsshopdata['status'])
        {
            $this->success('获取成功',$Goodsshopdata['data'],200);
        }else{
            $this->success('店铺不存在或已关','',200);
        }
    }
    /**
     * 评论
     */
    public function Userscomments()
    {
        $uid = $this->auth->id;
        $id = $this->request->param('id');
        $content = $this->request->param('content');
        $image = $this->request->param('image','');
        $type = $this->request->param('type');
        $score = $this->request->param('score',0);
        $order_id = $this->request->param('order_id','');
        $rules = [
            'content|评论内容' => 'require|min:8|max:80'
        ];
        $time = time();
        $data = [
            'gid' => $id,
            'content' => $content,
            'image' => $image,
            'goods_type' => $type,
            'score' => $score,
            'create_time' => $time,
        ];
        $Validate = new Validate($rules);
        if (!$Validate->check($data))
        {
            $this->success($Validate->getError(),'',400);
        }
        $UserModel = new UserModel();
        $user = $UserModel->getUser($uid);

        if (!$user)
        {
            $this->success('请从新登录','',401);
        }

        if ($user['status'] == 'hidden')
        {
            $this->success('目前无法评论请联系管理员','',400);
        }

        $data['uid'] = $user['id'];
        $data['name'] = $user['nickname'];
        $data['user_image'] = $user['avatar'];
        $GoodsComment = new GoodsCommentModel();
        $res = $GoodsComment->add($data);

        if ($res)
        {
            $this->success('评论成功',$res,200);
        }else{
            $this->success('评论失败','',400);
        }
    }
    /**
     * 用户收藏
     */
    public function Goodscollection()
    {
        $uid = $this->auth->id;
        $id = $this->request->param('id');
        $UserModel = new UserModel();
        $user = $UserModel->getUserInfo($uid);
        if (!$user) $this->success('请您先进行登录','',401);

        if (!$id) $this->success('选择您收藏的商品','',400);

        $GoodsModel = new GoodsModel();
        $goods = $GoodsModel->getGoodsDetail($user,$id);
        if (!$goods['status']) $this->success('该商品不存在','',400);
        $data = [
            'uid' => $uid,
            'gid' => $id,
            'type' => 'collect',
            'create_time' => time()
        ];
        $relation = $GoodsModel->addrelation($data);
        if ($relation)
        {
            $this->success('收藏成功',$relation,200);
        }else{
            $this->success('收藏失败','',200);
        }
    }
    /**
     * 收藏列表
     */
    public function relationlist()
    {
        $uid = $this->auth->id;
        $limit = $this->request->param('limit',20);
        $page = $this->request->param('page',1);
        $category = $this->request->param('category','');
        $name = $this->request->param('name','');
        if (!$uid) $this->success('请先登录','',401);
        $GoodsModel = new GoodsModel();
        $Goodsrelation = $GoodsModel->Getgoodsrelation($uid,$limit,$page,$category,$name);

        if ($Goodsrelation['count'] == 0)
        {
            $this->success('目前没有添加商品','',200);
        }else{
            $this->success('查询成功',$Goodsrelation,200);
        }
    }
    /**
     * 删除收藏
     */
    public function relationdel()
    {
        $uid = $this->auth->id;
        $ids = $this->request->param('ids');
        $type = $this->request->param('type',0);
        if(!$ids) $this->success('请选择操作的商品','',400);
        if (!$uid) $this->success('请先登录','',401);
        $GoodsModel = new GoodsModel();
        $res = $GoodsModel->Getrelationdel($uid,$ids,$type);
        if ($res)
        {
            $this->success('删除成功',$res,200);
        }else{
            $this->success('操作失败','',400);
        }

    }
}